// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  switch (event.action) {
    case 'create': {
      return create(event.data)
    }
    case 'mylist': {
      return mylist(event.data)
    }
    case 'uploadThumb': {
      return uploadThumb(event.data)
    }
    case 'detail': {
      return detail(event)
    }
    case 'wxcode': {
      return wxcode(event)
    }
    default: {
      return
    }
  }
}
async function create(data){
  const db=cloud.database();
  const _=db.command;
  const { OPENID } = cloud.getWXContext()
  const l=await db.collection("ad").where({
    _openid:OPENID,
    name: data.name
  }).count()
  if (l.total>0){
    return {
      error:true,
      errmsg:"数据已经存在"
    }
  }
  delete data.isAgree;
  res=await db.collection("ad").add(
    {
      data:[{
        ...data,
        _openid:OPENID
      }]
    }
  )
  return {res}
}
async function mylist(data){
  const db=cloud.database();
  const _=db.command;
  const { OPENID } = cloud.getWXContext()
  res=await db.collection("ad").where({_openid:OPENID}
  ).get();
  return res
}
async function uploadThumb(data){
  const db=cloud.database();
  const _=db.command;
  const { OPENID } = cloud.getWXContext()
  const l=await db.collection("ad").where({
    _openid:OPENID,
    _id: data._id
  }).count()
  if (l.total<0){
    return {
      error:true,
      errmsg:"数据不存在"
    }
  }
  console.log("更新uploadThumb",data)
  res=await db.collection("ad").where({
    _openid:OPENID,
    _id: data._id
  }).update(
    {
      data:{
        uploadThumb:data.uploadThumb
      }
    }
  )
  return {res}
}
async function search(event){
  const db=cloud.database();
  const _=db.command;
  const { OPENID } = cloud.getWXContext()
  res=await db.collection("collect").orderBy('date', 'desc').limit(1000).where({
    openId:OPENID
  }).get();
  return res
}
async function detail(event){
  console.log(event)
  const db=cloud.database();
  const _=db.command;
  const $ = db.command.aggregate
  const { OPENID } = cloud.getWXContext()
  res=await db.collection("chenyu").aggregate()
  .match({
    ChengYu:event.title
  })
  .lookup({
    from:"collect", //把tb_user用户表关联上_
    let: {
      order_book: '$ChengYu',
      order_quantity: '$quantity'
    },
    pipeline: $.pipeline()
      .match(_.expr($.and([
        $.eq(['$title', '$$order_book']),
       $.eq(['$openId', OPENID])
      ])))
      // .project({
      //   _id: 0,
      //   title: 1,
      //   openId:2
      // })
      .done(),
    // pipeline:$.pipeline()
    // .match(
    //   _.expr($.and([
    //     $.eq(['$title', '$$ChengYu_ChengYu']),
    //     $.gte(['$stock', OPENID])
    //   ]))
    // ).done(),
    // .match({
    //   $.eq(['$title','$$ChengYu_ChengYu']),
    //   $.eq(['$openId',OPENID])
    // }),
    // localField: 'ChengYu', //审批表的关联字段
    // foreignField: 'title', //用户表的关联字段
    as: 'collection', //匹配的结果作为uapproval相当于起个别名
  }).end()
  // .where({
  //   ChengYu:event.title
  // }).get();
  // const resCollect=await db.collection("collect")
  // .where({
  //   openId:OPENID,
  //   title:event.title
  // }).count();
  // if (resCollect.total>0) {
  //   res.collection=true
  // }else{
  //   res.collection=false
  // }
  return res
}
function wxcode(event){
  // 此处将获取永久有效的小程序码，并将其保存在云文件存储中，最后返回云文件 ID 给前端使用

  // const wxacodeResult = await cloud.openapi.wxacode.get({
  //   path: 'pages/openapi/openapi',
  // })

  // const fileExtensionMatches = wxacodeResult.contentType.match(/\/([^/]+)/)
  // const fileExtension = (fileExtensionMatches && fileExtensionMatches[1]) || 'jpg'

  // const uploadResult = await cloud.uploadFile({
  //   // 云文件路径，此处为演示采用一个固定名称
  //   cloudPath: `wxacode_default_openapi_page.${fileExtension}`,
  //   // 要上传的文件内容可直接传入图片 Buffer
  //   fileContent: wxacodeResult.buffer,
  // })

  // if (!uploadResult.fileID) {
  //   throw new Error(`upload failed with empty fileID and storage server status code ${uploadResult.statusCode}`)
  // }

  // return uploadResult.fileID
  return "cloud://chenyu-server.6368-chenyu-server-1304378709/wxacode_default_openapi_page.jpeg";
}